#include <stdio.h>
#include "libserialport.h"
#include <unistd.h>  // For sleep

int main() {
    struct sp_port *port;
    char *port_name = "/dev/ttyUSB3";
    char read_buf[256];
    int bytes_read;

    // 获取端口
    sp_get_port_by_name(port_name, &port);

    // 打开端口
    sp_open(port, SP_MODE_READ_WRITE);

    // 设置端口参数
    sp_set_baudrate(port, 115200);
    sp_set_bits(port, 8);
    sp_set_parity(port, SP_PARITY_NONE);
    sp_set_stopbits(port, 1);
    sp_set_flowcontrol(port, SP_FLOWCONTROL_NONE);

    // 写数据（非阻塞）
    const char *write_data1 = "ATI\r\n";
    const char *write_data2 = "AT+CPIN?\r\n";
    const char *write_data3 = "AT+QCCID\r\n";
    int bytes_written = sp_nonblocking_write(port, write_data1, strlen(write_data1));
    if (bytes_written > 0) {
        printf("Written: %d bytes\n", bytes_written);
    }

    static char test_cnt = 0;
    // 读数据（非阻塞）
    while (1) {
        bytes_read = sp_nonblocking_read(port, read_buf, sizeof(read_buf) - 1);
        if (bytes_read > 0) {
            read_buf[bytes_read] = '\0';
            printf("Read: %s\n", read_buf);
            // break;
            test_cnt++;
            if (test_cnt == 1)
            {
                bytes_written = sp_nonblocking_write(port, write_data1, strlen(write_data1));
                if (bytes_written > 0) {
                    printf("Written: %d bytes\n", bytes_written);
                }
            }
            else if(test_cnt == 2)
            {
                bytes_written = sp_nonblocking_write(port, write_data2, strlen(write_data2));
                if (bytes_written > 0) {
                    printf("Written: %d bytes\n", bytes_written);
                }
            }
            else if(test_cnt == 3)
            {
                bytes_written = sp_nonblocking_write(port, write_data3, strlen(write_data3));
                if (bytes_written > 0) {
                    printf("Written: %d bytes\n", bytes_written);
                }
                test_cnt = 0;
            }

        }
        sleep(1);  // 等待1秒再试
    }

    // 关闭端口
    sp_close(port);
    sp_free_port(port);

    return 0;
}


/**
 imx8编译指令，注意修改路径
 /opt/gcc-linaro-7.4.1-2019.02-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc -o main main.c -I/home/djq/mokar/cv2x_libs/libserialport-0.1.1/targets/imx8 -L/home/djq/mokar/cv2x_libs/libserialport-0.1.1/targets/imx8 -lserialport -Wl,-rpath=/home/djq/mokar/cv2x_libs/libserialport-0.1.1/targets/imx8
 */